/**
 * Created by easy on 15/5/11.
 */
/**
 * Created by easy on 15/4/6.
 */
$(document).ready(function () {
    pullToRefresh.init({
        loadingFunction: util.pullToRefresh
    });
    var formatDate = function (time) {
        if (time == null) {

        }
        if (typeof time != "number") {
            time = parseInt(time)
        }
        return mc.dealTime(time, "yyyy-MM-dd")
    };
    var setName = function (name) {
        return name.split(".")[0]
    };
    var getAjaxID = function (string) {
        if(string != undefined){
            return string.split("#")[1]
        }else{
            return "";
        }
    };
    var getAjaxStatus = function (string) {
        if(string != undefined){
            return string.split("#")[0]
        }else{
            return "";
        }
    };
    vars.ractiveRemarkList = new Ractive({
        el: "CONTAINER-remark",
        template: "#TEMPLATE-remark",
        data: {
            ractiveData: [],
            formatDate: function (time, format) {
                return mc.dealTime(parseInt(time), format);
            },
            setName: setName,
            getAjaxID: getAjaxID,
            getAjaxStatus: getAjaxStatus
        }
    });
    vars.ractiveAbnormalsList = new Ractive({
        el: "CONTAINER-abnormal",
        template: "#TEMPLATE-abnormal",
        data: {
            ractiveData: [],
            formatDate: function (time, format) {
                return mc.dealTime(parseInt(time), format);
            },
            setName: setName
        }
    });
});

(function () {
    vars.currentPage = 1;
    vars.pageSize = 10;
    basic.deviceReady = function () {
        var params = mc.getParamsFromURL(window.location);
        vars.processID = params.processID;
        vars.quantity = params.quantity;
        vars.orderID = params.orderID;
        $("#processName").html(params.processName);
        /*util.getOrderProcess(function () {
         mc.showContent();
         mc.syncData(["QC_PROCESS"], util.getOrderProcess);
         })*/
        mc.getDataFromLocalStorage("showProcessItem", function (data) {
            vars.currItem = parseInt(data)
            util.showTabByItem(parseInt(data));
        },"app");
        $("#btn-addabnormal").show();
        //mc.showContent();
    };
    //同步异常表，订单表，备注表，流程表，工厂表数据
    /*util.syncOrderDetailsData = function (callback) {
     mc.syncData(["QC_ORDER", "QC_ABNORMAL", "QC_REMARK", "QC_PROCESS", "QC_PARTY"], callback)
     };*/
    util.tabtoswitch = function (item, touchObj) {
        vars.currItem = item;
        mc.saveDataToLocalStorage("showProcessItem",item,function(){},"app");
        if ($(touchObj).hasClass("active") == false) {
            $("#btn-addabnormal").hide();
            $("#btn-addremark").hide();
            $(".mc-nodata").hide();
            $(touchObj).addClass("active").siblings(".tab-btn").removeClass("active");
            switch (item) {
                case 1:
                    util.getProcessAbnormals(function () {
                        mc.syncData(["QC_ABNORMAL"], util.getProcessAbnormals);
                    })
                    $(".view-abnormal").removeClass("no-display").siblings(".detail-view").addClass("no-display");
                    $("#btn-addabnormal").show();
                    break;
                case 2:
                    util.getProcessRemark(function () {
                        util.syncData(["QC_REMARK"], util.getProcessRemark)
                    });
                    $(".view-remark").removeClass("no-display").siblings(".detail-view").addClass("no-display");
                    $("#btn-addremark").show();

                    break;
            }
        }
    };
    util.showTabByItem = function (item) {
        $("#btn-addabnormal").hide();
        $("#btn-addremark").hide();
        $(".mc-nodata").hide();
        $($(".tab-btn")[item-1]).addClass("active");
        switch (item) {
            case 1:
                util.getProcessAbnormals(function () {
                    mc.syncData(["QC_ABNORMAL"], util.getProcessAbnormals);
                })
                $(".view-abnormal").removeClass("no-display").siblings(".detail-view").addClass("no-display");
                $(".view-abnormal").addClass("active").siblings(".tab-btn").removeClass("active");
                $("#btn-addabnormal").show();
                break;
            case 2:
                util.getProcessRemark(function () {
                    util.syncData(["QC_REMARK"], util.getProcessRemark)
                });
                $(".view-remark").removeClass("no-display").siblings(".detail-view").addClass("no-display");
                $(".view-remark").addClass("active").siblings(".tab-btn").removeClass("active");
                $("#btn-addremark").show();

                break;
        }
        mc.showContent()
    }
    util.getProcessRemark = function (callback) {
        var getOrdersRemarkCallback = function (data) {
            //alert(JSON.stringify(data))
            vars.ractiveRemarkList.data.ractiveData = data;
            vars.ractiveRemarkList.update("ractiveData");
            common.changePhotosProgress()
            var optionsForMorePage = {
                mode: "normal",
                dataLength: data.length,
                scrollContainer: $("#content"),
                callback: util.paginationOfRemarkList
            };
            common.morePage(optionsForMorePage);
            common.showPhotos(data);
            if (callback != undefined) {
                callback()
            }
        };
        var optionsForInitScrollList = {
            mode: "normal",
            scrollContainer: $("#content")
        };
        common.initScrollList(optionsForInitScrollList);
        var options = {
            orderID: vars.orderID,
            processID: vars.processID,
            currentPage: vars.currentPage,
            pageSize: vars.pageSize
        };
        service.getOrderProcessRemarkData(options, getOrdersRemarkCallback)
    };
    util.paginationOfRemarkList = function () {
        var paginationOfRemarkListCallback = function (data) {
            vars.ractiveRemarkList.data.ractiveData = $.merge(vars.ractiveRemarkList.data.ractiveData, data);
            vars.ractiveRemarkList.update("ractiveData");
            var optionsForMorePage = {
                mode: "normal",
                dataLength: data.length,
                scrollContainer: $("#content"),
                callback: util.paginationOfRemarkList
            };
            common.morePage(optionsForMorePage);
            util.showPhotos(data);
        };
        var options = {
            orderID: vars.orderID,
            processID: vars.processID,
            currentPage: vars.currentPage,
            pageSize: vars.pageSize
        };
        service.getOrderProcessRemarkData(options, paginationOfRemarkListCallback)
    };

    util.getProcessAbnormals = function (callback) {
        var getOrderAbnormalsCallback = function (data) {
            //alert(JSON.stringify(data))
            vars.ractiveAbnormalsList.data.ractiveData = data;
            vars.ractiveAbnormalsList.update("ractiveData");
            common.changePhotosProgress()
            var optionsForMorePage = {
                mode: "normal",
                dataLength: data.length,
                scrollContainer: $("#content"),
                callback: util.paginationOfAbnormalsList
            };
            common.morePage(optionsForMorePage);
            //util.showPhotos(data);
            if (callback != undefined) {
                callback()
            }
        };
        var optionsForInitScrollList = {
            mode: "normal",
            scrollContainer: $("#content")
        };
        common.initScrollList(optionsForInitScrollList);
        var options = {
            orderID: vars.orderID,
            processID: vars.processID,
            currentPage: vars.currentPage,
            pageSize: vars.pageSize
        };
        service.getOrderProcessAbnormalsData(options, getOrderAbnormalsCallback)
    };
    util.paginationOfAbnormalsList = function () {
        var paginationOfAbnormalsListCallback = function (data) {
            vars.ractiveAbnormalsList.data.ractiveData = $.merge(vars.ractiveAbnormalsList.data.ractiveData, data);
            vars.ractiveAbnormalsList.update("ractiveData");
            common.changePhotosProgress();
            var optionsForMorePage = {
                mode: "normal",
                dataLength: data.length,
                scrollContainer: $("#content"),
                callback: util.paginationOfAbnormalsList
            };
            common.morePage(optionsForMorePage);
            util.showPhotos(data);
        };
        var options = {
            orderID: vars.orderID,
            processID: vars.processID,
            currentPage: vars.currentPage,
            pageSize: vars.pageSize
        };
        service.getOrderProcessAbnormalsData(options, paginationOfAbnormalsListCallback)
    };

    util.pullToRefresh = function () {
        var view = parseInt($(".tab-btn.active").attr("value"));
        switch (view) {
            case 1:
                mc.syncData(["QC_ABNORMAL"], function () {
                    util.getProcessAbnormals(pullToRefresh.reset);
                });
                break;
            case 2:
                mc.syncData(["QC_REMARK"], function () {
                    util.getProcessRemark(pullToRefresh.reset);
                });
                break;
        }
    };
    util.showRemarkPhotosByIndex = function (jsonPK, currIndex) {
        var data = vars.ractiveRemarkList.data.ractiveData;
        common.showPhotosByIndex( jsonPK, currIndex);
    }
    util.ajaxStarted = function (ajaxID, matchIDs) {
        vars.type = "start";
        if(vars.currItem == 3){
            var remarkId = "remarkCreate" + ajaxID;
            var remarkObj = document.getElementById(remarkId);
            if(remarkObj) {
                var ajaxItem = $("#remarkCreate" + ajaxID);
                common.changeAjaxBadgeStatus(1, ajaxItem, "abnormalRemark", ajaxID);
            }
        }
        if(vars.currItem == 2) {
            var id = "abnormalCreate" + ajaxID;
            var obj = document.getElementById(id)
            if (obj) {
                var ajaxItem = $("#abnormalCreate" + ajaxID);
                common.changeAjaxBadgeStatus(1, ajaxItem, "abnormal", ajaxID);
            } else {
                util.changeAbnormalStatus(matchIDs);
            }
        }
        if(vars.currItem == 1){
            util.changeProcessSubmitStatus(matchIDs);
        }
        common.changePhotosProgress()
    };
    util.ajaxCompleted = function (ajaxID, result,  matchIDs) {
        vars.type = "complete";
        if(vars.currItem == 3){
            var remarkId = "remarkCreate" + ajaxID;
            var remarkObj = document.getElementById(remarkId);
            if(remarkObj) {
                var ajaxItem = $("#remarkCreate" + ajaxID);
                if(result == "success"){
                    common.changeAjaxBadgeStatus(2, ajaxItem, "orderRemark", ajaxID);
                } else if(result == "failed"){
                    common.changeAjaxBadgeStatus(3, ajaxItem, "orderRemark", ajaxID);
                }
            }
        }
        if(vars.currItem == 2){
            var id = "abnormalCreate"+ ajaxID;
            var obj = document.getElementById(id)
            if(obj){
                var ajaxItem = $("#abnormalCreate" + ajaxID);
                if(result == "success"){
                    common.changeAjaxBadgeStatus(2, ajaxItem, "abnormal", ajaxID,util.getAbnormalDetail);
                } else if(result == "failed"){
                    common.changeAjaxBadgeStatus(3, ajaxItem, "abnormal", ajaxID);
                }
            }else{
                util.changeAbnormalStatus(matchIDs);
            }
            if(vars.currItem == 1){
                util.changeProcessSubmitStatus(matchIDs);
            }
        }
        common.changePhotosProgress()
    };
    util.changeAbnormalStatus = function (matchIDs) {
        var matchIDsArr = matchIDs.split(",");
        for (var i = 0; i < matchIDsArr.length; i++) {
            var execFindStatus = function(){
                var abnormalID = matchIDsArr[i];
                var abnormalItem = $(document.getElementById(abnormalID));
                if (abnormalItem != undefined) {
                    var findAbnormalStatusCallback = function (data) {
                        //alert(JSON.stringify(data))
                        var descriptionStatus = data[0].descriptionStatus ? data[0].descriptionStatus.split("#")[0] : "";
                        var abnormalStatusStatus = data[0].abnormalStatusStatus ? data[0].abnormalStatusStatus.split("#")[0] : "";
                        var remarkStatus = data[0].remarkStatus ? data[0].remarkStatus.split("#")[0] : "";
                        var attachmentStatus = data[0].attachmentStatus ? data[0].attachmentStatus.split("#")[0] : "";
                        if (descriptionStatus == "uploading" || abnormalStatusStatus == "uploading" || remarkStatus == "uploading" || attachmentStatus == "uploading") {
                            common.changeAjaxBadgeStatus(1, abnormalItem, 'abnormal', abnormalID)
                        } else {
                            if (descriptionStatus == "failed" || abnormalStatusStatus == "failed" || remarkStatus == "failed" || attachmentStatus == "failed") {
                                common.changeAjaxBadgeStatus(3, abnormalItem, 'abnormal', abnormalID)
                            } else {
                                common.changeAjaxBadgeStatus(2, abnormalItem, 'abnormal', abnormalID)
                            }
                        }
                    };
                    var SQLOfFindAbnormalStatus = "SELECT descriptionStatus,abnormalStatusStatus,remarkStatus FROM QC_ABNORMAL WHERE jsonPK = ?;";
                    mc.execSQL(SQLOfFindAbnormalStatus, [abnormalID], findAbnormalStatusCallback);
                }
            };
            execFindStatus();
        }
    };

    util.findThisRemarkFailedTask = function (touchObj, remarkID) {
        var sql = "SELECT FCloudDataTransferID FROM T_CloudDataTransferCenter WHERE FCloudDataTransferMatchIDs LIKE '%" + remarkID + "%' AND FCloudDataTransferState = 'failed'";
        var findThisRemarkFailedTaskCallback = function (data) {
            //alert(JSON.stringify(data))
            for (var i = 0; i < data.length; i++) {
                data[i] = data[i].FCloudDataTransferID;
            }
            common.execUploadAjaxTask(touchObj, data);
        };
        mc.execSQL(sql, [], findThisRemarkFailedTaskCallback);
    };

    util.findThisAbnormalFailedTask = function (touchObj, abnormalID) {
        var sql = "SELECT FCloudDataTransferID FROM T_CloudDataTransferCenter WHERE FCloudDataTransferMatchIDs LIKE '%" + abnormalID + "%' AND FCloudDataTransferState = 'failed'";
        var findThisAbnormalsFailedTaskCallback = function (data) {
            //alert(JSON.stringify(data))
            for (var i = 0; i < data.length; i++) {
                data[i] = data[i].FCloudDataTransferID;
            }
            common.execUploadAjaxTask(touchObj, data);
        };
        mc.execSQL(sql, [], findThisAbnormalsFailedTaskCallback);
    };
})();